var srcOptions;
var desOptions;

$(document).ready(function(){
	//查询经营地址按扭事件
	$("#btn_search_place").click(function(){
		var keyword = $("#search_keyword").val();
		requestUrl = "../search_places";

		$.getJSON(requestUrl, {keyword:keyword,page_size:999}, function(data){
			var places = data.resultData.items;
			var place;
			var option;
			
			$("#slt_source").html("");

			for (var i = 0; i < places.length; i++) {
				place = places[i];
				
				if ($("#slt_destination option[value='" + place.id + "']").size() > 0) {
					continue;
				}
				
				option = document.createElement("option");
				option.value = place.id;
				option.text = place.placeName + "  " + place.address;
				
				$("#slt_source").append(option);
			}
		});
	});
	
	//选择经营地址按扭事件
	$("#btn_add_place_coop").click(function(){
		var selectedOption = $("#slt_source option:selected");
		$("#slt_destination").append(selectedOption);
		$("#place_ids").val($("#place_ids").val() + "," + selectedOption.val());
	});
});

function saveInitData() {
	srcOptions = document.getElementById("slt_source").cloneNode(true);
	desOptions = document.getElementById("slt_destination").cloneNode(true);
}

function restoreInitData() {
	document.getElementById("place_ids").value = "";
	document.getElementById("slt_source").options.length = 0;
	document.getElementById("slt_destination").options.length = 0;
	while (srcOptions.length > 0) {
		try {
			document.getElementById("slt_source").options.add(srcOptions.item(0));
		} catch (e) {
			var tmp = document.createElement('option');
            tmp.text = srcOptions[0].text;
            tmp.value = srcOptions[0].value; 
			document.getElementById("slt_source").options.add(tmp);
			srcOptions.options.remove(0);
		}
	}
	while (desOptions.length > 0) {
		try {
			document.getElementById("slt_destination").options.add(desOptions.item(0));
		} catch (e) {
			var tmp = document.createElement('option');
            tmp.text = desOptions[0].text;
            tmp.value = desOptions[0].value; 
			document.getElementById("slt_destination").options.add(tmp);
			desOptions.options.remove(0);
		}
	}
	saveInitData();
}

function changeTab(tabId) {
	document.getElementById('div_add_place').style.visibility = 'hidden';
	document.getElementById('div_add_place_coop').style.visibility = 'hidden';
	
	document.getElementById(tabId).style.visibility = 'visible';
}